<template>
  <div class="article-comment-section">
    <!-- 评论头部统计 -->
    <div class="comment-header">
      <div class="comment-count">
        <span class="count">{{ totalComments }}</span>
        <span class="label">条评论</span>
      </div>

      <!-- 排序选择 -->
      <div class="comment-sort">
        <el-dropdown @command="handleSortChange">
          <span class="sort-trigger">
            {{ getSortLabel(currentSort) }}
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="1">最新优先</el-dropdown-item>
              <el-dropdown-item command="2">最热优先</el-dropdown-item>
              <el-dropdown-item command="3">时间正序</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 发表评论区域 -->
    <div v-if="isLoggedIn" class="comment-publish">
      <CommentPublisher
        :article-id="articleId"
        :placeholder="'发表你的评论...'"
        @publish="handleCommentPublish"
      />
    </div>

    <!-- 未登录提示 -->
    <div v-else class="login-prompt">
      <div class="prompt-content">
        <el-icon><User /></el-icon>
        <span>请先登录后再发表评论</span>
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-loading="loading" class="comment-list">
      <!-- 显示的评论列表（前三条或全部） -->
      <div
        v-for="comment in displayedComments"
        :key="comment.id"
        class="comment-item"
      >
        <CommentItem
          :comment="comment"
          :article-id="articleId"
          :max-level="maxLevel"
          :children-limit="childrenLimit"
          :flat-replies="flatReplies"
          :active-reply-comment-id="activeReplyCommentId"
          :comment-images="getCommentImages(comment.id)"
          :images-loading="isImageLoading(comment.id)"
          @like="handleCommentLike"
          @reply="handleCommentReply"
          @delete="handleCommentDelete"
          @load-more-children="handleLoadMoreChildren"
          @toggle-reply="handleToggleReply"
          @reply-content-change="handleReplyContentChange"
        />
      </div>

      <!-- 查看全部评论按钮 -->
      <div v-if="shouldShowViewAllButton" class="view-all-comments">
        <el-button
          type="primary"
          :loading="expandLoading"
          class="view-all-btn"
          @click="handleViewAllComments"
        >
          <el-icon><ChatDotRound /></el-icon>
          查看全部{{ totalComments }}条评论
        </el-button>
      </div>

      <!-- 加载更多评论（展开状态下） -->
      <div v-if="showExpandedView && hasMore && !loading" class="load-more">
        <el-button :loading="loadingMore" @click="loadMoreComments">
          加载更多评论
        </el-button>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && allComments.length === 0" class="empty-state">
        <el-empty description="暂无评论，快来发表第一条评论吧！" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  onMounted,
  onUnmounted,
  watch,
  provide,
  nextTick
} from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowDown, User, ChatDotRound } from "@element-plus/icons-vue";
import type {
  ArticleCommentResponse,
  CommentTreeQuery,
  CreateCommentRequest,
  LikeCommentRequest
} from "@/api/user-comment";
import {
  getCommentTreeApi,
  createCommentApi,
  likeCommentApi,
  deleteCommentApi,
  UserCommentUtils,
  isApiResponseSuccess
} from "@/api/user-comment";
import {
  getBatchCommentImagesApi,
  type CommentImageInfo
} from "@/api/comment-image";
import { useUserAuthStore } from "@/store/modules/userAuth";
import { CommentItem, CommentPublisher } from "@/components/UserComment";

// Props定义
interface Props {
  /** 文章ID */
  articleId: number;
  /** 最大评论层级 */
  maxLevel?: number;
  /** 每个根评论显示的回复数量 */
  childrenLimit?: number;
  /** 每页评论数量 */
  pageSize?: number;
  /** 是否扁平化回复 */
  flatReplies?: boolean;
  /** 回复排序方式 */
  replySortType?: number;
  /** 初始显示的评论数量 */
  initialDisplayCount?: number;
}

const props = withDefaults(defineProps<Props>(), {
  maxLevel: 2,
  childrenLimit: 5,
  pageSize: 10,
  flatReplies: true,
  replySortType: 1,
  initialDisplayCount: 3
});

// Emits定义
const emit = defineEmits<{
  commentCountChange: [count: number];
}>();

// 用户认证store
const userAuthStore = useUserAuthStore();

// 响应式数据
const loading = ref(false);
const loadingMore = ref(false);
const expandLoading = ref(false);
const allComments = ref<ArticleCommentResponse[]>([]); // 所有评论
const currentSort = ref(1); // 默认最新优先
const totalComments = ref(0);
const currentPage = ref(1);
const hasMore = ref(false);
const showExpandedView = ref(false); // 是否显示展开视图

// 全局回复状态管理
const activeReplyCommentId = ref<number | null>(null);
const replyContentStates = ref<Map<number, boolean>>(new Map());

// 图片缓存管理
const commentImagesCache = ref<Map<number, CommentImageInfo[]>>(new Map());
const imageLoadingStates = ref<Map<number, boolean>>(new Map());

// 计算属性
const isLoggedIn = computed(() => userAuthStore.isLoggedIn);

// 显示的评论列表
const displayedComments = computed(() => {
  if (showExpandedView.value) {
    // 展开状态显示所有已加载的评论
    return allComments.value;
  } else {
    // 初始状态只显示前面指定数量的评论
    return allComments.value.slice(0, props.initialDisplayCount);
  }
});

// 是否应该显示"查看全部评论"按钮
const shouldShowViewAllButton = computed(() => {
  return (
    !showExpandedView.value &&
    totalComments.value > props.initialDisplayCount &&
    allComments.value.length > props.initialDisplayCount
  );
});

// 批量加载评论图片
const loadCommentImagesBatch = async (
  commentList: ArticleCommentResponse[]
) => {
  try {
    // 收集所有需要加载图片的评论ID
    const collectCommentIds = (
      comments: ArticleCommentResponse[]
    ): number[] => {
      const ids: number[] = [];

      for (const comment of comments) {
        ids.push(comment.id);

        // 递归收集子评论ID
        if (comment.children && comment.children.length > 0) {
          ids.push(...collectCommentIds(comment.children));
        }
      }

      return ids;
    };

    const allCommentIds = collectCommentIds(commentList);

    // 过滤出尚未加载图片的评论ID
    const unloadedIds = allCommentIds.filter(
      id => !commentImagesCache.value.has(id)
    );

    if (unloadedIds.length === 0) {
      console.log("🖼️ 所有评论图片已缓存，无需重新加载");
      return;
    }

    console.log(`🖼️ 批量加载 ${unloadedIds.length} 个评论的图片:`, unloadedIds);

    // 标记正在加载
    unloadedIds.forEach(id => imageLoadingStates.value.set(id, true));

    // 批量获取图片
    const response = await getBatchCommentImagesApi(unloadedIds);

    if (response.code === 200 && response.data) {
      // 将图片数据存入缓存
      Object.entries(response.data).forEach(([commentId, images]) => {
        const id = parseInt(commentId);
        commentImagesCache.value.set(id, images);
        imageLoadingStates.value.set(id, false);
      });

      console.log(
        `🖼️ 成功缓存 ${Object.keys(response.data).length} 个评论的图片`
      );
    } else {
      console.warn("🖼️ 批量获取评论图片失败:", response.message);
      // 标记加载失败的评论
      unloadedIds.forEach(id => {
        commentImagesCache.value.set(id, []);
        imageLoadingStates.value.set(id, false);
      });
    }
  } catch (error) {
    console.error("🖼️ 批量加载评论图片异常:", error);
    // 清理加载状态
    imageLoadingStates.value.clear();
  }
};

// 获取评论图片（从缓存）
const getCommentImages = (commentId: number): CommentImageInfo[] => {
  return commentImagesCache.value.get(commentId) || [];
};

// 检查图片是否正在加载
const isImageLoading = (commentId: number): boolean => {
  return imageLoadingStates.value.get(commentId) || false;
};

// 提供图片数据给子组件
provide("commentImagesCache", commentImagesCache);
provide("imageLoadingStates", imageLoadingStates);
provide("getCommentImages", getCommentImages);
provide("isImageLoading", isImageLoading);

// 获取排序标签
const getSortLabel = (sortType: number): string => {
  const labels = {
    1: "最新优先",
    2: "最热优先",
    3: "时间正序"
  };
  return labels[sortType] || "最新优先";
};

// 构建查询参数
const buildQuery = (page: number = 1): CommentTreeQuery => ({
  articleId: props.articleId,
  current: page,
  size: props.pageSize,
  maxLevel: props.maxLevel,
  childrenLimit: props.childrenLimit,
  sortType: currentSort.value,
  replySortType: props.replySortType,
  flatReplies: props.flatReplies,
  rootOnly: false
});

// 递归计算评论总数（包括所有回复）
const calculateTotalComments = (
  commentList: ArticleCommentResponse[]
): number => {
  let total = 0;
  for (const comment of commentList) {
    total += 1; // 计算当前评论
    if (comment.children && comment.children.length > 0) {
      total += calculateTotalComments(comment.children); // 递归计算子评论
    }
  }
  return total;
};

// 对评论列表排序，将当前登录用户的评论置顶
const sortCommentsWithUserFirst = (
  commentList: ArticleCommentResponse[]
): ArticleCommentResponse[] => {
  const currentUserId = userAuthStore.userId;
  if (!currentUserId) return commentList;

  // 分离当前用户的评论和其他评论
  const userComments: ArticleCommentResponse[] = [];
  const otherComments: ArticleCommentResponse[] = [];

  commentList.forEach(comment => {
    // 检查评论作者ID（支持多种字段名）
    const authorId = comment.author?.userId || comment.user?.userId;
    if (authorId === currentUserId) {
      userComments.push(comment);
    } else {
      otherComments.push(comment);
    }
  });

  // 用户评论在前，其他评论在后
  return [...userComments, ...otherComments];
};

// 加载评论数据
const loadComments = async (reset: boolean = true) => {
  try {
    loading.value = true;

    const query = buildQuery(reset ? 1 : currentPage.value);
    console.log("📝 加载评论参数:", query);

    const response = await getCommentTreeApi(query);
    console.log("📝 评论数据响应:", response);

    // 检查后端响应格式
    if (isApiResponseSuccess(response) && response.data) {
      const pageData = response.data;
      console.log("📝 分页数据:", pageData);
      console.log("📝 评论记录:", pageData.records);
      console.log("📝 评论数量:", pageData.records?.length);

      if (reset) {
        // 将当前用户的评论置顶
        const sortedComments = sortCommentsWithUserFirst(
          pageData.records || []
        );
        allComments.value = sortedComments;
        currentPage.value = 1;
      } else {
        // 加载更多时，也需要对新加载的评论进行排序后再合并
        const newComments = pageData.records || [];
        const sortedNewComments = sortCommentsWithUserFirst(newComments);
        allComments.value.push(...sortedNewComments);
      }

      // 计算评论总数
      const backendTotal = pageData.total || 0;
      const calculatedTotal = calculateTotalComments(allComments.value);

      // 使用后端返回的total，但如果看起来不正确，则使用计算值
      if (backendTotal >= calculatedTotal) {
        totalComments.value = backendTotal;
      } else {
        console.warn("📝 后端返回的total可能不包含回复，使用计算值:", {
          backendTotal,
          calculatedTotal
        });
        totalComments.value = calculatedTotal;
      }

      hasMore.value = pageData.hasNext || false;
      currentPage.value = pageData.current || 1;

      console.log("📝 更新后的评论列表:", allComments.value);
      console.log("📝 评论总数 (修复后):", totalComments.value);

      // 通知父组件评论数变化
      emit("commentCountChange", totalComments.value);

      // 批量加载评论图片
      if (allComments.value.length > 0) {
        // 延迟加载图片，避免阻塞页面渲染
        setTimeout(() => {
          loadCommentImagesBatch(allComments.value);
        }, 100);
      }

      // 评论加载完成后，处理 hash 滚动
      await nextTick();
      scrollToHashElement();
    } else if (
      response &&
      (response.success === false || (response.code && response.code !== 200))
    ) {
      // 处理API返回的错误
      console.error("📝 API返回错误:", response.message);
      ElMessage.error(response.message || "获取评论失败");
    } else {
      // 处理其他异常情况
      console.warn("📝 响应数据格式异常:", response);
      ElMessage.error("获取评论失败，数据格式异常");
    }
  } catch (error) {
    console.error("加载评论失败:", error);
    ElMessage.error(UserCommentUtils.formatErrorMessage(error));
  } finally {
    loading.value = false;
    loadingMore.value = false;
    expandLoading.value = false;
  }
};

// 处理查看全部评论
const handleViewAllComments = async () => {
  expandLoading.value = true;

  try {
    // 如果当前评论数少于总评论数，需要加载更多
    if (allComments.value.length < totalComments.value) {
      // 计算需要加载多少页来获取所有评论
      const totalPages = Math.ceil(totalComments.value / props.pageSize);

      // 加载剩余页面的评论
      for (
        let page = currentPage.value + 1;
        page <= Math.min(totalPages, currentPage.value + 3);
        page++
      ) {
        currentPage.value = page;
        await loadComments(false);
      }
    }

    // 切换到展开视图
    showExpandedView.value = true;

    console.log("📝 展开评论列表，显示全部评论");
  } catch (error) {
    console.error("展开评论失败:", error);
    ElMessage.error("展开评论失败");
  } finally {
    expandLoading.value = false;
  }
};

// 加载更多评论（展开状态下）
const loadMoreComments = async () => {
  if (loadingMore.value || !hasMore.value) return;

  loadingMore.value = true;
  currentPage.value += 1;
  await loadComments(false);
};

// 处理排序变化
const handleSortChange = (sortType: string) => {
  const newSort = parseInt(sortType);
  if (newSort !== currentSort.value) {
    currentSort.value = newSort;
    showExpandedView.value = false; // 排序变化时收起展开视图
    loadComments(true);
  }
};

// 处理评论发表
const handleCommentPublish = (newComment: ArticleCommentResponse) => {
  // 将新评论添加到列表顶部
  allComments.value.unshift(newComment);

  // 重新排序，确保当前用户的评论在顶部
  allComments.value = sortCommentsWithUserFirst(allComments.value);

  // 重新计算总评论数
  totalComments.value = calculateTotalComments(allComments.value);

  // 通知父组件评论数变化
  emit("commentCountChange", totalComments.value);

  // 显示成功提示
  ElMessage.success("评论发表成功");
};

// 处理评论点赞
const handleCommentLike = async (commentId: number) => {
  try {
    const comment = findCommentById(commentId);
    if (!comment) {
      console.error("找不到评论:", commentId);
      return;
    }

    // 防止重复点击
    if (comment.isLiking) return;
    comment.isLiking = true;

    // 计算新的点赞状态（切换当前状态）
    const newLikeStatus = !comment.isLiked;

    console.log("🔥 点赞操作:", {
      commentId,
      currentLiked: comment.isLiked,
      newLikeStatus: newLikeStatus,
      likeCount: comment.likeCount
    });

    const request: LikeCommentRequest = {
      commentId,
      liked: newLikeStatus
    };

    console.log("📤 发送点赞请求:", request);
    const response = await likeCommentApi(request);
    console.log("📥 点赞API响应:", response);

    if (isApiResponseSuccess(response)) {
      // 更新本地状态
      comment.isLiked = newLikeStatus;
      comment.likeCount += newLikeStatus ? 1 : -1;

      console.log("✅ 点赞成功，更新本地状态:", {
        commentId,
        newLiked: comment.isLiked,
        newCount: comment.likeCount
      });

      ElMessage.success(newLikeStatus ? "点赞成功" : "取消点赞成功");
    } else {
      console.error("❌ 点赞API响应异常:", response);
      ElMessage.error("点赞操作失败");
    }
  } catch (error) {
    console.error("点赞评论失败:", error);
    ElMessage.error(UserCommentUtils.formatErrorMessage(error));
  } finally {
    const comment = findCommentById(commentId);
    if (comment) {
      comment.isLiking = false;
    }
  }
};

// 处理评论回复
const handleCommentReply = (newReply: ArticleCommentResponse) => {
  // 找到父评论并添加回复
  const parentComment = findCommentById(newReply.parentId!);
  if (parentComment) {
    parentComment.children.push(newReply);
    parentComment.replyCount += 1;
    parentComment.childrenTotal += 1;
  }

  // 重新计算总评论数
  totalComments.value = calculateTotalComments(allComments.value);

  // 通知父组件评论数变化
  emit("commentCountChange", totalComments.value);

  // 清理回复状态 - 发布成功后自动收起回复框（静默关闭，不触发警告）
  if (activeReplyCommentId.value !== null) {
    const replyCommentId = activeReplyCommentId.value;
    replyContentStates.value.delete(replyCommentId);
    activeReplyCommentId.value = null;
  }

  ElMessage.success("回复发表成功");
};

// 处理评论删除
const handleCommentDelete = async (commentId: number) => {
  // 保存当前滚动位置
  const scrollPosition =
    window.pageYOffset || document.documentElement.scrollTop;

  try {
    await ElMessageBox.confirm(
      "确定要删除这条评论吗？删除后无法恢复。",
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false,
        appendTo: document.body,
        customClass: "delete-confirm-dialog",
        beforeClose: (action, instance, done) => {
          // 在关闭前恢复滚动位置
          setTimeout(() => {
            window.scrollTo(0, scrollPosition);
          }, 50);
          done();
        }
      }
    );

    const response = await deleteCommentApi(commentId);

    if (isApiResponseSuccess(response)) {
      // 从列表中移除评论
      removeCommentFromList(commentId);

      // 重新计算总评论数
      totalComments.value = calculateTotalComments(allComments.value);

      // 通知父组件评论数变化
      emit("commentCountChange", totalComments.value);

      ElMessage.success("评论删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除评论失败:", error);
      ElMessage.error(UserCommentUtils.formatErrorMessage(error));
    }
  }
};

// 处理加载更多子评论
const handleLoadMoreChildren = (commentId: number) => {
  // 这个功能在当前文档中没有定义，暂时不实现
  console.log("加载更多子评论:", commentId);
};

// 处理回复状态切换
const handleToggleReply = (commentId: number) => {
  console.log(
    "🔄 切换回复状态:",
    commentId,
    "当前活跃:",
    activeReplyCommentId.value
  );

  // 如果点击的是当前活跃的回复框
  if (activeReplyCommentId.value === commentId) {
    // 检查当前回复框是否有内容
    const hasContent = replyContentStates.value.get(commentId) || false;

    if (hasContent) {
      // 有内容时不允许收起，提示用户
      ElMessage.warning("请先发布评论或清空输入内容后再收起");
      return;
    } else {
      // 没有内容时可以正常收起
      activeReplyCommentId.value = null;
      replyContentStates.value.delete(commentId);
    }
  } else {
    // 切换到新的回复框时，检查之前的回复框是否有内容
    if (activeReplyCommentId.value !== null) {
      const previousCommentId = activeReplyCommentId.value;
      const previousHasContent =
        replyContentStates.value.get(previousCommentId) || false;

      if (previousHasContent) {
        // 之前的回复框有内容，不允许切换
        ElMessage.warning("请先完成当前回复或清空输入内容");
        return;
      } else {
        // 清理之前的状态
        replyContentStates.value.delete(previousCommentId);
      }
    }

    // 切换到新的回复框
    activeReplyCommentId.value = commentId;
    // 初始化新回复框的状态
    replyContentStates.value.set(commentId, false);
  }
};

// 处理回复内容变化
const handleReplyContentChange = (data: {
  commentId: number;
  hasContent: boolean;
}) => {
  console.log("📝 回复内容变化:", data);
  replyContentStates.value.set(data.commentId, data.hasContent);
};

// 根据ID查找评论（递归查找）
const findCommentById = (commentId: number): ArticleCommentResponse | null => {
  const findInList = (
    list: ArticleCommentResponse[]
  ): ArticleCommentResponse | null => {
    for (const comment of list) {
      if (comment.id === commentId) {
        return comment;
      }
      if (comment.children?.length > 0) {
        const found = findInList(comment.children);
        if (found) return found;
      }
    }
    return null;
  };

  return findInList(allComments.value);
};

// 从列表中移除评论（递归移除）
const removeCommentFromList = (commentId: number): boolean => {
  const removeFromList = (list: ArticleCommentResponse[]): boolean => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].id === commentId) {
        list.splice(i, 1);
        return true;
      }
      if (list[i].children?.length > 0) {
        if (removeFromList(list[i].children)) {
          list[i].replyCount -= 1;
          list[i].childrenTotal -= 1;
          return true;
        }
      }
    }
    return false;
  };

  return removeFromList(allComments.value);
};

// 监听文章ID变化
watch(
  () => props.articleId,
  () => {
    if (props.articleId) {
      showExpandedView.value = false; // 重置展开状态
      loadComments(true);
    }
  },
  { immediate: true }
);

// 处理点击外部区域关闭回复框
const handleClickOutside = (event: Event) => {
  // 如果没有活跃的回复框，不需要处理
  if (!activeReplyCommentId.value) return;

  const target = event.target as HTMLElement;

  // 检查点击的元素是否在回复相关的区域内
  const isClickInsideReply =
    target.closest(".reply-editor") ||
    target.closest(".reply-action") ||
    target.closest(".comment-publisher") ||
    // 排除表情选择器相关的区域
    target.closest(".emoji-popover") ||
    target.closest(".emoji-picker-trigger") ||
    target.closest(".el-popover") ||
    target.closest(".simple-emoji-picker") ||
    // 排除Element Plus的弹窗容器
    target.closest(".el-popper") ||
    target.closest("[data-popper-placement]");

  // 如果点击在回复区域外，关闭回复框
  if (!isClickInsideReply) {
    console.log("🖱️ 点击外部区域，关闭回复框");
    activeReplyCommentId.value = null;
  }
};

// 处理 hash 滚动定位
const scrollToHashElement = () => {
  const hash = route.hash;
  if (hash) {
    console.log("🔖 尝试滚动到 hash 位置:", hash);

    // 多次尝试查找元素，因为 DOM 可能还在渲染中
    let attempts = 0;
    const maxAttempts = 10;
    const attemptScroll = () => {
      const element = document.querySelector(hash);
      if (element) {
        console.log("✅ 找到评论元素，开始滚动");
        element.scrollIntoView({
          behavior: "smooth",
          block: "center"
        });
        return true;
      }

      attempts++;
      if (attempts < maxAttempts) {
        setTimeout(attemptScroll, 200);
      } else {
        console.warn("⚠️ 未找到评论元素:", hash);
      }
      return false;
    };

    setTimeout(attemptScroll, 100);
  }
};

// 路由实例
const route = useRoute();

// 组件挂载后初始化
onMounted(() => {
  // 移除手动调用，依靠 watch immediate: true 来加载数据

  // 添加全局点击监听器
  document.addEventListener("click", handleClickOutside);
});

// 组件卸载时清理监听器
onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>

<style scoped lang="scss">
@use "@/styles/user-theme.scss" as *;

.article-comment-section {
  @include mobile {
    @include mobile-card;

    padding: 16px;
    margin-top: 16px;
    border-radius: 8px;
  }

  @include mobile-xs {
    padding: 12px;
    margin-top: 12px;
  }

  padding: 24px;
  margin-top: 32px;
  background: #fff;
  border-radius: 12px;

  .comment-header {
    @include mobile {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
      padding-bottom: 12px;
      margin-bottom: 16px;
    }

    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 16px;
    margin-bottom: 24px;

    .comment-count {
      .count {
        @include mobile {
          font-size: 18px;
        }

        @include mobile-xs {
          font-size: 16px;
        }

        font-size: 20px;
        font-weight: 700;
        color: #1d2129;
      }

      .label {
        @include mobile {
          font-size: 14px;
        }

        @include mobile-xs {
          font-size: 13px;
        }

        margin-left: 6px;
        font-size: 16px;
        color: #8a919f;
      }
    }

    .comment-sort {
      @include mobile {
        align-self: flex-end;
      }

      .sort-trigger {
        @include mobile {
          @include mobile-button;

          min-height: 32px;
          padding: 6px 10px;
          font-size: 13px;
        }

        @include mobile-xs {
          min-height: 28px;
          padding: 4px 8px;
          font-size: 12px;
        }

        display: flex;
        gap: 6px;
        align-items: center;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: 500;
        color: #8a919f;
        cursor: pointer;
        background: #f2f3f5;
        border-radius: 20px;
        transition: all 0.2s ease;

        &:hover {
          color: #1d2129;
          background: #e9ecef;
        }
      }
    }
  }

  .comment-publish {
    @include mobile {
      margin-bottom: 16px;
    }

    @include mobile-xs {
      margin-bottom: 12px;
    }

    margin-bottom: 24px;
  }

  .login-prompt {
    @include mobile {
      @include mobile-card;

      padding: 16px;
      margin-bottom: 20px;
    }

    @include mobile-xs {
      padding: 12px;
      margin-bottom: 16px;
    }

    padding: 24px;
    margin-bottom: 32px;
    text-align: center;
    background: #f8f9fa;
    border-radius: 8px;

    .prompt-content {
      @include mobile {
        @include mobile-text;

        gap: 6px;
      }

      @include mobile-xs {
        gap: 4px;
        font-size: 13px;
      }

      display: flex;
      gap: 8px;
      align-items: center;
      justify-content: center;
      font-size: 15px;
      color: #8a919f;

      .el-icon {
        @include mobile {
          font-size: 16px;
        }

        @include mobile-xs {
          font-size: 14px;
        }

        font-size: 18px;
      }
    }
  }

  .comment-list {
    .comment-item {
      @include mobile {
        margin-bottom: 12px;
      }

      @include mobile-xs {
        margin-bottom: 10px;
      }

      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .view-all-comments {
      @include mobile {
        padding: 16px 0;
        margin-top: 16px;
      }

      @include mobile-xs {
        padding: 12px 0;
        margin-top: 12px;
      }

      padding: 20px 0;
      margin-top: 24px;
      text-align: center;
      border-top: 1px solid #ebeef5;

      .view-all-btn {
        @include mobile {
          @include mobile-button;

          min-width: 180px;
          padding: 10px 20px;
          font-size: 14px;
        }

        @include mobile-xs {
          min-width: 160px;
          padding: 8px 16px;
          font-size: 13px;
        }

        min-width: 200px;
        padding: 12px 24px;
        font-size: 15px;
        font-weight: 500;
        background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
        border: none;
        border-radius: 24px;
        box-shadow: 0 4px 12px rgb(64 158 255 / 30%);
        transition: all 0.3s ease;

        .el-icon {
          @include mobile {
            margin-right: 4px;
            font-size: 14px;
          }

          margin-right: 6px;
          font-size: 16px;
        }

        &:hover {
          background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
          box-shadow: 0 6px 16px rgb(64 158 255 / 40%);
          transform: translateY(-2px);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }

    .load-more {
      @include mobile {
        // 使用外层的 margin-top
      }

      @include mobile-xs {
        // 使用外层的 margin-top
      }

      margin-top: 32px;
      text-align: center;

      .el-button {
        @include mobile {
          @include mobile-button;

          width: 100%;
          max-width: 200px;
          padding: 10px 24px;
          font-size: 14px;
        }

        @include mobile-xs {
          padding: 8px 20px;
          font-size: 13px;
        }

        padding: 12px 32px;
        font-size: 15px;
        font-weight: 500;
        color: #1e80ff;
        background: #f2f6ff;
        border-color: #e1ecff;
        border-radius: 24px;
        transition: all 0.2s ease;

        &:hover {
          background: #e6f3ff;
          border-color: #b3d9ff;
          transform: translateY(-1px);
        }
      }
    }

    .empty-state {
      @include mobile {
        padding: 40px 0;
      }

      @include mobile-xs {
        padding: 30px 0;
      }

      padding: 60px 0;
      color: #8a919f;
      text-align: center;

      .el-icon {
        @include mobile {
          margin-bottom: 12px;
          font-size: 36px;
        }

        @include mobile-xs {
          margin-bottom: 8px;
          font-size: 32px;
        }

        margin-bottom: 16px;
        font-size: 48px;
        color: #c9cdd4;
      }

      .empty-text {
        @include mobile {
          @include mobile-text;

          margin-bottom: 6px;
        }

        @include mobile-xs {
          margin-bottom: 4px;
          font-size: 13px;
        }

        margin-bottom: 8px;
        font-size: 16px;
      }

      .empty-desc {
        @include mobile {
          font-size: 13px;
        }

        @include mobile-xs {
          font-size: 12px;
        }

        font-size: 14px;
        color: #c9cdd4;
      }
    }
  }
}

// 暗色主题适配
.dark {
  .article-comment-section {
    background: #1e1e28;

    .comment-header {
      .comment-count {
        .count {
          color: #e5e6eb;
        }

        .label {
          color: #86909c;
        }
      }

      .comment-sort {
        .sort-trigger {
          color: #86909c;
          background: #2a2a3a;

          &:hover {
            color: #e5e6eb;
            background: #3a3a4a;
          }
        }
      }
    }

    .comment-list {
      .view-all-comments {
        border-color: #404040;

        .view-all-btn {
          background: linear-gradient(135deg, #4c63d2 0%, #6366f1 100%);
          box-shadow: 0 4px 12px rgb(76 99 210 / 40%);

          &:hover {
            background: linear-gradient(135deg, #3730a3 0%, #4338ca 100%);
            box-shadow: 0 6px 16px rgb(76 99 210 / 50%);
          }
        }
      }

      .load-more {
        .el-button {
          color: #1e80ff;
          background: #2a2a3a;

          &:hover {
            color: #fff;
            background: #1e80ff;
          }
        }
      }

      .empty-state {
        color: #86909c;

        .el-icon {
          color: #4a5568;
        }

        .empty-desc {
          color: #4a5568;
        }
      }
    }

    .login-prompt {
      background: #2a2a3a;

      .prompt-content {
        color: #86909c;
      }
    }
  }
}
</style>

<style lang="scss">
// 全局样式：删除确认对话框简洁白色背景
.delete-confirm-dialog.el-message-box {
  background: #fff !important;
  border: 1px solid #e1e5e9;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgb(0 0 0 / 10%) !important;
}

.delete-confirm-dialog .el-message-box__header {
  padding: 20px 20px 10px;
  background: #fff !important;
  border-bottom: 1px solid #f1f2f3;
}

.delete-confirm-dialog .el-message-box__content {
  padding: 10px 20px 20px;
  background: #fff !important;
}

.delete-confirm-dialog .el-message-box__title {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a !important;
}

.delete-confirm-dialog .el-message-box__message {
  font-size: 14px;
  line-height: 1.6;
  color: #2c3e50 !important;
}

.delete-confirm-dialog .el-message-box__btns {
  padding: 10px 20px 20px;

  .el-button {
    font-weight: 500;
    border-radius: 8px;

    &.el-button--primary {
      background: linear-gradient(135deg, #007fff 0%, #0056b3 100%);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
      }
    }

    &.el-button--default {
      color: #606266;
      background: #fff;
      border: 1px solid #dcdfe6;

      &:hover {
        color: #409eff;
        background: #f5f7fa;
        border-color: #c6e2ff;
      }
    }
  }
}

// 对话框遮罩层
.el-overlay {
  background-color: rgb(0 0 0 / 50%) !important;
}
</style>
